<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>canvas</title>
    <style>
        #myCanvas {
            border: 1px solid red;
        }
    </style>
</head>
<body>
<canvas id="myCanvas">
    您的浏览器不支持Canvas，请升级浏览器
</canvas>
<script>
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    ctx.canvas.width = 600;
    ctx.canvas.height = 400;
    var str = "hello world";
    //设置文本样式
    ctx.font = "bold 30px sans-serif";
    //水平对齐,left,center,right
    ctx.textAlign = "center";

    //垂直对齐,top,middle,bottom
    ctx.textBaseline = "top";

    //获取文字宽度
    var width=ctx.measureText(str).width;
    console.log(width)

    ctx.fillStyle = "#FF0000";

    //填充文本
    ctx.fillText(str, 300, 100);
    ctx.strokeStyle = "#0000FF";

    //描边文本
    ctx.strokeText(str, 300, 300);
</script>
</body>
</html>